<template>
  <el-card shadow="never">
    <template #header>{{ props.name }}</template>
    <el-form ref="formRef" :model="form" label-width="160px">
      <div :style="props.grid ? 'display: flex; flex-wrap: wrap;' : ''">
        <div v-for="field in fields" :style="`width:${field.width ? field.width : '100%'}`">
          <div v-if="field.type === 'title'" :style="field.props">{{ field.label }}</div>
          <template v-else-if="field.type !== 'list'">
            <field v-model="form[field.prop]" :config="field" />
          </template>
          <template v-else>
            <field-list v-model="form[field.prop]" :config="field" />
          </template>
        </div>
      </div>
      <el-form-item>
        <el-button v-for="btn in props.actions" :type="btn.type" @click="handle(btn, formRef)">
          {{ btn.label }}
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts" setup>
import { reactive, ref, watch } from 'vue';
import Field from './field.vue';
import FieldList from './field-table.vue';
import type { FieldType } from './type.d';
const formRef = ref();
const props = defineProps<{
  name: string;
  fields: FieldType[];
  actions: any[];
  grid?: boolean;
  modelValue: any;
}>();
const form = reactive(props.modelValue);
const fields: FieldType[] = props.fields;

const emit = defineEmits(['update:modelValue', 'handle']);

watch(
  () => props.modelValue,
  () => {
    form.value = props.modelValue;
  },
  { deep: true }
);
watch(
  form,
  () => {
    emit('update:modelValue', form.value);
  },
  { deep: true, immediate: true }
);

const handle = (btn, formRef) => {
  emit('handle', btn.event, formRef);
};
</script>
